#include <iostream>
#include <limits>

using std::cout;
using std::endl;
using std::cin;

class Complex
{
public:
    Complex(double dreal = 0.0, double dimag = 0.0)
    : _dreal(dreal)
    , _dimag(dimag)
    {
        cout << "Complex(double = 0.0, double = 0.0)" << endl;
    }

    ~Complex()
    {
        cout << "~Complex()" << endl;
    }

    friend std::ostream &operator<<(std::ostream &os, const Complex &rhs);
    friend std::istream &operator>>(std::istream &is, Complex &rhs);
private:
    double _dreal;
    double _dimag;
};

std::ostream &operator<<(std::ostream &os, const Complex &rhs)
{
    cout << "std::ostream &operator<<(std::ostream &, const Complex &)" << endl;
    if(0 == rhs._dreal && 0 == rhs._dimag)
    {
        os << 0 << endl;
    }
    else if(0 == rhs._dreal)
    {
        os << rhs._dimag << "i" << endl;
    }
    else
    {
        os << rhs._dreal;
        if(rhs._dimag > 0)
        {
            os << " + " << rhs._dimag << "i" << endl;
        }
        else if(0 == rhs._dimag)
        {
            os << endl;
        }
        else
        {
            os << " - " << (-1) * rhs._dimag << "i" << endl;
        }
    }

    return os;
}

void readDouble(std::istream &is, double &number)
{
    while(is >> number, !is.eof())//真值表达式
    {
        if(is.bad())
        {
            cout << "stream is bad" << endl;
            return;
        }
        else if(is.fail())
        {
            is.clear();
            is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            cout << "pls input double data" << endl;
        }
        else 
        {
            cout << "number = " << number << endl;
            break;
        }
    }
}

std::istream &operator>>(std::istream &is, Complex &rhs)
{
    cout << "std::istream &operator>>(std::istream &, Complex &)" << endl;
    readDouble(is, rhs._dreal);
    readDouble(is, rhs._dimag);

    return is;
}

void test2()
{
    Complex c(2, 3);
    cout << "c = " << c << endl;

    cout << endl << endl;
    Complex c2;
    cin >> c2;
    cout << "c2 = " << c2 << endl;
}


int main(int argc, char *argv[])
{
    test2();
    return 0;
}

